from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListAPIView
from rest_framework.permissions import *
from rest_framework.response import Response

from apps.meiduo_admin.utils import UserDefinePagination
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import *
from apps.meiduo_admin.serializers.image import SKUImageSerializer, SKUSerializer


class ImageViewSet(ModelViewSet):

    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSerializer
    pagination_class = UserDefinePagination

    # 图片上传 使用的 fdfs 重写写入方法
    def create(self, request, *args, **kwargs):
        # 根据配置文件建立 fdfs 链接
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 获取 前端上传的图片资源
        data = request.FILES.get("image")
        # 上传图片到 fdfs
        result = client.upload_by_buffer(data.read())
        # 判断上传成功与否
        if result["Status"] != "Upload successed.":
            return Response(status=403)
        # 获取上传后的路径
        image_url = result["Remote file_id"]
        # 获取 sku_id
        sku_id = request.data.get("sku")
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 返回结果
        return Response(
            {
                'id': img.id,
                'sku': sku_id,
                'image': img.image.url
            },
            status=201  # 前端需要接受201状态
        )

    # 图片修改
    def update(self, request, *args, **kwargs):
        # 建立 fdfs 对象链接
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 获取 图片资源
        data = request.FILES.get("image")
        # 获取 sku_id
        sku_id = request.data.get("sku")
        # 上传图片值 fdfs
        result = client.upload_by_buffer(data.read())
        # 判断上传是否成功
        if result["Status"] != "Upload successed.":
            return Response(status=403)
        # 获取上传后的路径
        image_url = result["Remote file_id"]
        # 查询 对象
        img = SKUImage.objects.get(id=kwargs['pk'])
        img.image = image_url
        img.save()
        # 返回结果
        return Response(
            {
                'id': img.id,
                'sku': sku_id,
                'image': img.image.url
            },
            status=201  # 前端需要接受201状态码
        )


class SKUListView(ListAPIView):
    permission_classes = [IsAuthenticated]
    queryset = SKU.objects.all()
    serializer_class = SKUSerializer

